const {
	chmod
} = require("fs");
const utils = require("self-utils");
const db = uniCloud.database();
const cmd = db.command;
module.exports = {
	_before: async function() { // 通用预处理器
		this.userInfo = await utils.getUserInfo(this);
		if (!this.userInfo.uid) throw this.userInfo;
	},
	async createOrder(data) {
		data.user_id = this.userInfo.uid;
		data.order_no = getOrderId();

		try {
			await db.collection("wanshop-mall-order").add(data);
			return data.order_no;
		} catch (error) {
			// 错误处理
			console.error("Failed to create order:", error);
			throw new Error("Failed to create order.");
		}
	},
	
	async updateOutOrderNo(data){
		let orderInfo = {...data}
		console.log(orderInfo);
		await db.collection("wanshop-mall-order").where({order_no:orderInfo.order_no}).update({
			out_trade_no:orderInfo.out_trade_no
		})
		
	},
	
	
	
	async getOrderList() {
		try {
			return await db.collection("wanshop-mall-order").where({
				user_id: this.userInfo.uid,
				// status:cmd.neq(0)
			}).orderBy("createTime", "desc").get()
		} catch (error) {
			console.error("Failed to fetch order list:", error);
		}

	},
	// 获取全部订单
	async getOrderAll() {
		try {
			return await db.collection("wanshop-mall-order").orderBy("createTime", "desc").get()
		} catch (error) {
			console.error("Failed to fetch order list:", error);
		}
	},
	
	
	async updateDone(id){
		if(!this.userInfo.role.includes('manage')){
			return {msg:"没有权限",code:-1}
		};
		return await db.collection("wanshop-mall-order").doc(id).update({
			done:true
		})
	},
	
	async _timing(){
		let time = Date.now() - 3600
		await db.collection("wanshop-mall-order").where({
			status:0,
			createTime:cmd.lt(time)
		}).remove()
		await db.collection("uni-pay-orders").where({
			status:0,
			create_date:cmd.lt(time)
		}).remove()		
	},
	
	// async orderRefund(id){
	// 	if(!this.userInfo.role.includes('manage')){
	// 		return {msg:"没有权限",code:-1}
	// 	};
	// 	db.collection("wanshop-mall-order").where({
	// 		out_trade_no:id
	// 	}).
	// }
}

function getOrderId() {
	// 获取当前时间
	const now = new Date();

	// 转换为UTC+8时区的时间
	const utc8Time = new Date(now.getTime() + (8 * 60 * 60 * 1000));

	const year = utc8Time.getFullYear().toString();
	const month = ("0" + (utc8Time.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以要加1
	const day = ("0" + utc8Time.getDate()).slice(-2);
	const hours = ("0" + utc8Time.getHours()).slice(-2);
	const minutes = ("0" + utc8Time.getMinutes()).slice(-2);
	const seconds = ("0" + utc8Time.getSeconds()).slice(-2);

	// 组合年月日时分秒
	const timePart = year + month + day + hours + minutes + seconds;

	// 获取随机数部分
	const randomPart = String(Math.random()).substring(3, 9);

	return timePart + "_" + randomPart;
}